<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 顶部添加和搜索区域 -->
      <el-row :gutter="8">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <i slot="append" class="el-input__icon el-icon-search" @click="getUserList"></i>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%" stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeSwitch(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="edituser(scope.row.id)"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-s-tools"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户文本框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClose">
        <el-form ref="addFormRef" :model="addFormList" label-width="80px" :rules="addFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addFormList.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addFormList.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addFormList.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addFormList.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 文本框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDialog">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户文本框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="editDialogClose"
      >
        <el-form ref="editFormRef" :model="editFormList" label-width="80px" :rules="editFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editFormList.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFormList.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editFormList.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 文本框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDialg">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRolesDialogVisible"
        width="30%"
        @close="setRolesClose"
      >
        <div>
          <p>当前的用户:{{userInfo.username}}</p>
          <p>当前的角色:{{userInfo.role_name}}</p>
          <p>
            分配新角色:
            <el-select v-model="setRolesid" placeholder="请选择">
              <el-option
                v-for="item in setRolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRolesSub">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    var checkMoblie = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的电话"));
    };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      addFormList: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加表单预校验
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱不正确，请重新输入",
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            validator: checkMoblie,
            message: "手机号码不正确，请重新输入",
            trigger: "blur"
          }
        ]
      },
      editFormList: {},
      // 修改表单预校验
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱不正确，请重新输入",
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            validator: checkMoblie,
            message: "手机号码不正确，请重新输入",
            trigger: "blur"
          }
        ]
      },
      // 分配角色对话框
      setRolesDialogVisible: false,

      setRolesList: [],
      // 用户数据
      userInfo: {},
      // 已选中的角色id值
      setRolesid: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取列表失败");
      this.userList = res.data.users;
      // console.log(this.userList);
      this.total = res.data.total;
    },
    // 每页显示几条
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getUserList();
    },
    // 改变页数
    handleCurrentChange(newnum) {
      this.queryInfo.pagenum = newnum;
      this.getUserList();
    },
    // 更新用户状态
    async changeSwitch(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        this.$message.error("更新状态失败");
      }

      this.$message.success("更新状态成功");
    },
    // 重置添加、
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    }, // 添加用户
    addDialog() {
      // 先表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addFormList);
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.addDialogVisible = false;
        this.getUserList();
        this.$message.success("添加用户成功");
      });
    },
    // 重置编辑文本框
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 通过id获取用户信息
    async edituser(id) {
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.editFormList = res.data;
    },
    // 编辑用户
    editDialg() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editFormList.id,
          {
            email: this.editFormList.email,
            mobile: this.editFormList.mobile
          }
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("更新失败");
        }
        this.getUserList();
        this.editDialogVisible = false;
        this.$message.success("更新成功");
      });
    },
    // 删除功能
    async deleteUser(id) {
      // 返回的是一个params对象
      const confirmStr = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmStr);
      if (confirmStr !== "confirm") return;
      const { data: res } = await this.$http.delete("users/" + id);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.getUserList();
      this.$message.success("删除成功");
    },
    // 分配角色
    async setRoles(userInfo) {
      console.log(userInfo);
      this.userInfo = userInfo;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      console.log(res.data);
      this.setRolesList = res.data;
      this.setRolesDialogVisible = true;
    },
    // 点击确定按钮发起请求
    async setRolesSub() {
      if (!this.setRolesid) {
        this.$message.error("请选择分配的角色");
        return;
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.setRolesid }
      );
      // console.log(res.data);
      if (res.meta.status !== 200) return this.$message.error("更新角色失败");
      this.getUserList();
      this.setRolesDialogVisible = false;
    },
    // 关闭对话框重置表单
    setRolesClose() {
      this.setRolesid = "";
      this.userInfo = {};
    }
  }
};
</script>
<style lang="less" scoped>
.el-pagination {
  margin-top: 12px;
}
</style>
